import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import logo from '../../assets/logo.png'
import styles from './index.module.scss'
import { useDispatch } from 'react-redux'
import { useState } from 'react'
import { login } from '@/store/actions/login'
import { useHistory, useLocation } from 'react-router-dom'

const Login = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const location = useLocation()
  const [isLogin, setIsLogin] = useState(false)
  console.log('从上一个页面调过来的时候，带的参数是', location)
  const onFinish = async (values) => {
    console.log('表单中的数据是', values)
    // 通过了表单校验，做登录
    const { mobile, code } = values
    try {
      setIsLogin(true)
      // 登录
      await dispatch(login({ mobile, code }))
      // 提示
      message.success('登录成功', 0.5, () => {
        // alert('跳转')
        let pathname = '/home'
        if (location.state) {
          pathname = location.state.backto
        }
        history.push(pathname)
        // history.push(location.state?.backto || '/home')
      })
    } catch (err) {
      // console.dir(err)
      message.error(err.response.data.message, 0.5)
    } finally {
      setIsLogin(false)
    }
  }
  return (
    <div className={styles.root}>
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          autoComplete="off"
          size="large"
          onFinish={onFinish}
          initialValues={{
            mobile: 13811111111,
            code: '246810',
            agree: true
          }}>
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: '手机号不能为空' },
              { pattern: /^1\d{10}$/, message: '手机号不合法' }
            ]}>
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              { required: true, message: '验证码不能为空' },
              { pattern: /^\d{6}$/, message: '验证码不合法' }
            ]}>
            <Input placeholder="请输入验证码" />
          </Form.Item>

          <Form.Item
            name="agree"
            valuePropName="checked"
            rules={[
              {
                validator (rule, value) {
                  console.log(rule, value)
                  if (value) {
                    return Promise.resolve()
                  } else {
                    return Promise.reject(new Error('您必须同意~~'))
                  }
                }
              }
            ]}>
            <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button loading={isLogin} type="primary" htmlType="submit" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
